package com.fan.gofast.util;

import com.alibaba.fastjson.JSON;
import com.fan.gofast.constant.Metadata;
import com.fan.gofast.constant.ResultEnum;
import com.fan.gofast.dtos.BaseResponse;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * @author G7
 */
public class ResponseUtils {

    private static final String PARAM_ERROR_FORMAT = "%s(%s)";

    public static <T> BaseResponse<T> error() {
        return new BaseResponse<>(ResultEnum.REQUEST_HANDLE_FAILURE.code,
                ResultEnum.REQUEST_HANDLE_FAILURE.message);
    }

    public static <T> BaseResponse<T> error(ResultEnum resultEnum) {
        return new BaseResponse<>(resultEnum.code, resultEnum.message);
    }

    public static <T> BaseResponse<T> error(int code, String message) {
        return new BaseResponse<>(code, message);
    }

    public static <T> BaseResponse<T> error(ResultEnum resultEnum, T data) {
        return new BaseResponse<>(resultEnum.code, resultEnum.message, data);
    }

    public static <T> BaseResponse<T> success() {
        return new BaseResponse<>(Metadata.SUCCESS_CODE,"处理成功");
    }

    public static <T> BaseResponse<T> success(T data) {
        BaseResponse<T> resp = new BaseResponse<>();
        resp.setData(data);
        return resp;
    }

    public static <T> BaseResponse<T> success(ResultEnum resultEnum) {
        return new BaseResponse<>(resultEnum.code, resultEnum.message);
    }



    /**
     * 从List<A> copy到List<B>
     *
     * @param list  List<B>
     * @param clazz B
     * @return List<B>
     */
    public static <T> List<T> beanCopy(List<?> list, Class<T> clazz) {
        if (Objects.isNull(list)) {
            return Collections.EMPTY_LIST;
        }
        String oldOb = JSON.toJSONString(list);
        return JSON.parseArray(oldOb, clazz);
    }


    /**
     * 成功响应
     *
     * @param response
     * @param <R>
     * @return
     */
    public static <R> boolean isSuccess(BaseResponse<R> response) {
        return ResultEnum.SUCCESS.code == response.getCode();
    }

    /**
     * 失败响应
     *
     * @param response
     * @param <R>
     * @return
     */
    public static <R> boolean isFail(BaseResponse<R> response) {
        if (Objects.isNull(response)) {
            return true;
        }
        return ResultEnum.SUCCESS.code != response.getCode();
    }


    /**
     * 参数错误
     *
     * @param paramName
     * @param <T>
     * @return
     */
    public static <T> BaseResponse<T> paramException(String paramName) {
        return error(ResultEnum.PARAM_ERROR.code,
                String.format(PARAM_ERROR_FORMAT, ResultEnum.PARAM_ERROR.message, paramName));
    }

}
